/*
 * Copyright 2025-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package demo;

import glz.hawkgenerator.database.SqlFile;
import glz.hawkgenerator.database.dialect.Dialect;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static glz.hawkdesigner.project.ProjectHelper.srcGeneratedResources;
import static glz.hawkgenerator.database.dialect.Dialect.MYSQL;
import static glz.hawkgenerator.database.dialect.Dialect.ORACLE;

/**
 * This class is responsible for
 *
 * @author Zhang Peng
 */
public class DatabaseGeneratorApplication {

    public static void main(String[] args) throws IOException {
        Path path = currentProjectRootPath();

        generateDdl(ORACLE);
        generateDdl(MYSQL);
    }

    public static Path currentProjectRootPath() {
        return Paths.get("").toAbsolutePath();
    }

    private static void generateDdl(Dialect dialect) throws IOException {
        System.out.printf("--------------------------%s------------------------------%n", dialect.name());
        SqlFile sqlFile = SqlFile.builder(Database.INSTANCE.databaseSpec, dialect).build();

        //输出到console
        sqlFile.writeTo(System.out);

        //输出到File
        Path path = srcGeneratedResources(currentProjectRootPath().resolve("database-generator-demo"))
                .resolve(String.format("ddl/bookstore-%s.sql", dialect.name().toLowerCase()));
        sqlFile.writeTo(getFile(path));
        System.out.println();
    }

    private static File getFile(Path path) throws IOException {
        File file = path.toFile();
        if (file.exists()) {
            Files.deleteIfExists(file.toPath());
        }
        return file;
    }

}
